use std::collections::HashMap;

pub fn converter(input: &str, tp: &str) -> String {
    // 资源文件来自 https://github.com/BYVoid/OpenCC/ 和 zhcdict
    let characters = std::fs::read_to_string("TSCharacters.txt").unwrap();
    let phrases = std::fs::read_to_string("TSPhrases.txt").unwrap();

    let phrases_iter = phrases.split('\n').filter_map(|x| x.split_once(" "));
    let characters_iter = characters
        .split('\n')
        .filter_map(|x| x.split_once("\t"))
        .map(|(x, y)| (x.chars().next().unwrap(), y.chars().next().unwrap()));
    match tp {
        "t2s" => {
            for (t, s) in phrases_iter {
                if t == input {
                    return s.to_string();
                }
            }

            let characters_map = characters_iter.collect::<HashMap<_, _>>();
            input
                .chars()
                .map(|x| characters_map.get(&x).copied().unwrap_or(x))
                .collect()
        }
        "s2t" => {
            for (t, s) in phrases_iter {
                if s == input {
                    return t.to_string();
                }
            }

            let characters_map = characters_iter
                .map(|(t, s)| (s, t))
                .collect::<HashMap<_, _>>();
            input
                .chars()
                .map(|x| characters_map.get(&x).copied().unwrap_or(x))
                .collect()
        }
        _ => {
            unreachable!()
        }
    }
}
